package com.innerchic.apt.base;

import com.google.auto.service.AutoService;
import com.innerchic.annotations.base.BindViewLayoutHolder;
import com.innerchic.apt.tool.BaseAbstractProcessor;
import com.innerchic.apt.tool.Path;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;

/**
 * ================================================
 * 作    者：贾恒飞 >>> 17515250730@163.com
 * 项    目：young
 * 日    期：2021/11/1 15:23
 * 包    名：com.innerchic.apt.base
 * 描    述：绑定view页面布局的apt
 * Create by zFox from AndroidStudio4.2
 * ================================================
 */
@AutoService(Processor.class)
public class BindViewLayoutHolderApt extends BaseAbstractProcessor {

    @Override
    public Set<String> getSupportedAnnotationTypes() {
        HashSet<String> supportTypes = new LinkedHashSet<>();
        supportTypes.add(BindViewLayoutHolder.class.getCanonicalName());
        return supportTypes;
    }

    /**
     * 代码集合列表
     */
    private final List<BindViewLayoutHolderCoder> coderList = new ArrayList<>();

    @Override
    public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
        logPut("processing......");
        String homeLayoutPath = Path.getLayoutPath();

        //得到所有的注解
        Set<? extends Element> elements = getElementsAnnotatedWith(roundEnvironment, BindViewLayoutHolder.class);
        for (Element element : elements) {
            BindViewLayoutHolder annotation = element.getAnnotation(BindViewLayoutHolder.class);
            String layoutName = annotation.value();
            if (!layoutName.endsWith(".xml")) layoutName = layoutName + ".xml";
            String layoutPath = homeLayoutPath + layoutName;
            TypeElement classElement = (TypeElement) element;
            BindViewLayoutHolderCoder createJavaCode = new BindViewLayoutHolderCoder(baseElements, classElement);
            try {
                BufferedReader br = new BufferedReader(new FileReader(new File(layoutPath)));
                String line;
                String typeName = "";
                while ((line = br.readLine()) != null) {
                    if (line.trim().equals("")) continue;
                    line = line.trim();
                    if (line.startsWith("<") && !line.startsWith("</")) {
                        typeName = line.replace("<", "");
                        if (typeName.contains("xmlns:android")) {
                            //标识是底层类
                            typeName = typeName.substring(0, typeName.indexOf("xmlns:android")).trim();
                        }
                        continue;
                    }
                    //去注释代码
                    if (line.startsWith("<!--") && line.endsWith("-->")) continue;
                    if (line.startsWith("android:id")) {
                        String substring;
                        if (line.contains("@+id/")) {
                            substring = line.substring(line.indexOf("@+id/"));
                        } else substring = line.substring(line.indexOf("@id/"));
                        substring = substring.replace("@+id/", "").replace("@id/", "").trim();
                        if (substring.endsWith("\"")) {
                            substring = substring.replace("\"", "");
                        }
                        logPut("Type:" + typeName + ",id:" + substring);
                        createJavaCode.putElement(substring, typeName);
                    }
                }
                coderList.add(createJavaCode);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        for (BindViewLayoutHolderCoder createJavaCode : coderList) {
            try {
                JavaFileObject jfo = processingEnv.getFiler().createSourceFile(createJavaCode.getProxyClassFullName(), createJavaCode.getTypeElement());
                Writer writer = jfo.openWriter();
                writer.write(createJavaCode.generateJavaCode());
                writer.flush();
                writer.close();
            } catch (IOException e) {
                logPut(" --> create " + createJavaCode.getProxyClassFullName() + "error");
            }
        }

        return false;
    }

}
